<template>
  <div class="overview-report">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="overview-stats">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ overviewData.total_users || 0 }}</div>
            <div class="stat-label">
              总用户数
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 300px; line-height: 1.5;">
                  <div><strong>总用户数</strong></div>
                  <div style="margin-top: 8px;">
                    <div>• <strong>统计范围：</strong>平台注册的所有用户</div>
                    <div>• <strong>包含内容：</strong>通过NFC、推荐等方式注册的用户</div>
                    <div>• <strong>更新频率：</strong>实时更新</div>
                    <div>• <strong>变化趋势：</strong>与上期对比的增减情况</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: help;"></i>
              </el-tooltip>
            </div>
            <div class="stat-change" :class="overviewData.users_change_type">
              {{ overviewData.users_change }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ overviewData.total_points || 0 }}</div>
            <div class="stat-label">
              总积分发放
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 300px; line-height: 1.5;">
                  <div><strong>总积分发放</strong></div>
                  <div style="margin-top: 8px;">
                    <div>• <strong>统计范围：</strong>平台发放的所有积分</div>
                    <div>• <strong>包含内容：</strong>注册奖励、推荐奖励、消费奖励、签到奖励等</div>
                    <div>• <strong>计算方式：</strong>累计发放积分总数</div>
                    <div>• <strong>变化趋势：</strong>与上期对比的增减情况</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: help;"></i>
              </el-tooltip>
            </div>
            <div class="stat-change" :class="overviewData.points_change_type">
              {{ overviewData.points_change }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">¥{{ overviewData.total_commission || 0 }}</div>
            <div class="stat-label">
              总佣金金额
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 300px; line-height: 1.5;">
                  <div><strong>总佣金金额</strong></div>
                  <div style="margin-top: 8px;">
                    <div>• <strong>统计范围：</strong>平台产生的所有佣金</div>
                    <div>• <strong>包含内容：</strong>推荐佣金、消费佣金、活动佣金等</div>
                    <div>• <strong>计算方式：</strong>累计佣金金额总和</div>
                    <div>• <strong>货币单位：</strong>人民币（元）</div>
                    <div>• <strong>变化趋势：</strong>与上期对比的增减情况</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: help;"></i>
              </el-tooltip>
            </div>
            <div class="stat-change" :class="overviewData.commission_change_type">
              {{ overviewData.commission_change }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ overviewData.active_campaigns || 0 }}</div>
            <div class="stat-label">
              活跃活动数
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 300px; line-height: 1.5;">
                  <div><strong>活跃活动数</strong></div>
                  <div style="margin-top: 8px;">
                    <div>• <strong>统计范围：</strong>当前正在进行的活动</div>
                    <div>• <strong>活跃标准：</strong>状态为启用且在有效期内的活动</div>
                    <div>• <strong>包含类型：</strong>推广活动、优惠活动、积分活动等</div>
                    <div>• <strong>更新频率：</strong>实时更新</div>
                    <div>• <strong>变化趋势：</strong>与上期对比的增减情况</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: help;"></i>
              </el-tooltip>
            </div>
            <div class="stat-change" :class="overviewData.campaigns_change_type">
              {{ overviewData.campaigns_change }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">用户增长趋势</div>
          <div id="userTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">积分发放趋势</div>
          <div id="pointsTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">佣金分布</div>
          <div id="commissionDistChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">活动效果对比</div>
          <div id="campaignCompareChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { nfcReportsAPI } from '@/api/nfc'
import ChartMixin from '../mixins/ChartMixin'

export default {
  name: 'OverviewReport',
  mixins: [ChartMixin],
  props: {
    filters: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      overviewData: {}
    }
  },
  watch: {
    filters: {
      handler() {
        this.loadData()
      },
      deep: true
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData() {
      try {
        const params = { ...this.filters }
        await this.loadOverviewData(params)
      } catch (error) {
        console.error('加载综合概览数据失败：', error)
        this.$message.error('加载数据失败')
      }
    },

    // 加载概览数据
    async loadOverviewData(params) {
      const response = await nfcReportsAPI.getOverviewDashboard(params)
      const raw = response.data || {}
      const commission = raw.commission || {}
      const commissionStats = commission.stats || {}
      const points = raw.points || {}
      const pointsStats = points.stats || {}

      // 将后端返回的数据映射为概览区使用的扁平结构
      this.overviewData = {
        // 顶部四格（优先使用后端扁平字段）
        total_users: Number(raw.total_users || pointsStats.account_count || 0),
        total_points: Number(raw.total_points || pointsStats.total_earned_points || pointsStats.total_current_points || 0),
        total_commission: Number(commissionStats.total_amount || 0),
        active_campaigns: Number(raw.active_campaigns || 0),

        // 环比/同比占位（可后续由后端提供）
        users_change: raw.users_change || '',
        users_change_type: raw.users_change_type || '',
        points_change: raw.points_change || '',
        points_change_type: raw.points_change_type || '',
        commission_change: raw.commission_change || '',
        commission_change_type: raw.commission_change_type || '',
        campaigns_change: raw.campaigns_change || '',
        campaigns_change_type: raw.campaigns_change_type || '',

        // 图表所需数据（使用后端返回的趋势/对比）
        user_trend_dates: raw.user_trend_dates || [],
        user_trend_values: raw.user_trend_values || [],
        points_trend_dates: raw.points_trend_dates || [],
        points_trend_values: raw.points_trend_values || [],
        campaign_names: raw.campaign_names || [],
        campaign_effectiveness: raw.campaign_effectiveness || [],

        // 佣金分布饼图：按已结算/待结算拆分
        commission_distribution: [
          { name: '已结算', value: Number(commissionStats.settled_amount || 0) },
          { name: '待结算', value: Number(commissionStats.pending_amount || 0) }
        ],

        // 补充：时间范围展示需要可用
        period_start: (raw.period_info && raw.period_info.start_date) || '',
        period_end: (raw.period_info && raw.period_info.end_date) || ''
      }

      this.$nextTick(() => {
        this.renderOverviewCharts()
      })
    },

    // 渲染概览图表
    renderOverviewCharts() {
      // 用户增长趋势图
      this.renderChart('userTrendChart', {
        title: { text: '' },
        xAxis: { type: 'category', data: this.overviewData.user_trend_dates || [] },
        yAxis: { type: 'value' },
        series: [{
          data: this.overviewData.user_trend_values || [],
          type: 'line',
          smooth: true,
          itemStyle: { color: '#409EFF' }
        }]
      })

      // 积分发放趋势图
      this.renderChart('pointsTrendChart', {
        title: { text: '' },
        xAxis: { type: 'category', data: this.overviewData.points_trend_dates || [] },
        yAxis: { type: 'value' },
        series: [{
          data: this.overviewData.points_trend_values || [],
          type: 'line',
          smooth: true,
          itemStyle: { color: '#67C23A' }
        }]
      })

      // 佣金分布饼图
      this.renderChart('commissionDistChart', {
        title: { text: '' },
        series: [{
          type: 'pie',
          data: this.overviewData.commission_distribution || [],
          radius: '70%'
        }]
      })

      // 活动效果对比柱状图
      this.renderChart('campaignCompareChart', {
        title: { text: '' },
        xAxis: {
          type: 'category',
          data: this.overviewData.campaign_names || [],
          axisLabel: {
            interval: 'auto', // 自动间隔，避免重叠
            rotate: 45, // 旋转45度
            fontSize: 12,
            margin: 8
          }
        },
        yAxis: {
          type: 'value',
          name: '效果评分',
          nameTextStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        grid: {
          bottom: 80, // 增加底部空间，为旋转的标签留出空间
          left: 60,
          right: 30,
          top: 30
        },
        series: [{
          data: this.overviewData.campaign_effectiveness || [],
          type: 'bar',
          itemStyle: { color: '#E6A23C' },
          barWidth: '60%'
        }]
      })
    },

  }
}
</script>

<style scoped>
.overview-report {
  padding: 0;
}

.overview-stats {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-change {
  font-size: 12px;
}

.stat-change.increase {
  color: #67C23A;
}

.stat-change.decrease {
  color: #F56C6C;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  min-height: 360px;
}

.chart-card .el-card__header {
  font-weight: bold;
  color: #333;
}
</style>